package com.swak.zookeeper;

import org.apache.curator.framework.CuratorFramework;

import com.swak.codec.Encodes;
import com.swak.config.ConfigService;
import com.swak.registry.URL;

/**
 * 配置服务
 * 
 * @author 618lf
 */
public class ZookeeperConfig implements ConfigService {

	private final ZookeeperService zookeeperService;
	private final CuratorFramework client;

	public ZookeeperConfig(ZookeeperService zookeeperService) {
		this.zookeeperService = zookeeperService;
		this.client = zookeeperService.getOriginalZookeeperClient();
	}

	@Override
	public String listen(URL url, com.swak.config.ChangeListener listener) throws Exception {
		String path = url.toCategoryPath();
		this.zookeeperService.create(path, false);
		this.zookeeperService.addDataListener(path, (key, value, eventType) -> {
			if (path.equals(key)) {
				listener.configChange(String.valueOf(value));
			}
		});
		return this.getConfig(url);
	}

	@Override
	public String getConfig(URL url) throws Exception {
		String path = url.toCategoryPath();
		return this.getConfig(path);
	}

	@Override
	public String getConfig(String path) throws Exception {
		return Encodes.encode(this.client.getData().forPath(path));
	}
}
